<template>
  <div class="listen-book">
    <TopHeader @back="headerBack" @share="headerShare" id="top"></TopHeader>
    <div class="p-3">
      <img :src="'./src/assets/image/31.jpg'" alt="" class="book-cover">
      <span class="font-bold text-xl mt-2 text-center txtover1">大灭绝时代</span>
      <scroll class="wrapper-lyric" :data="lyricList" ref="bscroll">
        <ul class="content">
          <li v-for="(item, i) in lyricList" :style="{color: lyricIndex === i ? 'black' : '#ded9d9',
         'font-weight':lyricIndex === i ? 'bold' : ''}" class="text-center" :key="i" :data-index='i'
              style="margin-top: 10px" v-touch:tap="touchHandler"
              :ref="setItemRef">
            {{ item.txt }}
          </li>
        </ul>
      </scroll>
    </div>
    <div class="fixed w-full bottom-0  bg-white py-3 px-5" id="bottom">
      <audio :src="audioSrc" ref="audioPlayer"></audio>
      <div class="flex mx-3 items-center justify-center mb-6" style="height: 18px">
        <span class="text-sm font-sans mr-2">{{ currentTimeStr }}</span>
        <!--        <div class="flex-1 mx-2 bg-gray-200 " style="height: 2px;">-->
        <!--          <div class="bg-black" style="height: 3px;" :style="{'width': `${vdProgress}%`}">-->
        <!--          </div>-->
        <!--        </div>-->
        <van-slider v-model="vdProgress" @change="onSliderChange" active-color="black" bar-height="3px"
                    button-size="10px">
          <!--          <template #button>-->
          <!--          </template>-->
        </van-slider>
        <span class="text-sm font-sans ml-2">{{ endTimeStr }}</span>
      </div>
      <div class="flex items-center justify-around ">
        <van-icon name="wap-nav" size="20"/>
        <div class="text-sm">
          <i class="iconfont icon-yueduqi_shangyizhang font-bold"></i>
        </div>
        <van-icon name="play-circle" size="50" v-show="!playing" @click="onPlay()"/>
        <van-icon name="pause-circle" size="50" v-show="playing" @click="onPause()"/>
        <div class="text-sm">
          <i class="iconfont icon-yueduqi_xiayizhang font-bold"></i>
        </div>
        <van-icon name="comment-o" size="20"/>
      </div>
    </div>
    <van-share-sheet
        v-model:show="showShare"
        title="立即分享给好友"
        :options="shareOptions"
        @select="onShareSelect"
    />
  </div>
</template>

<script lang="ts" setup>
import {reactive, toRefs, ref, onBeforeUpdate, onUpdated, onMounted, nextTick, watch} from "vue";
import Lyric from 'lyric-parser'
import {useRect} from '@vant/use';
import {loadFile} from '../util/common'

const currentTime = ref(0)
const bottomHeight = ref('0px')
const topHeight = ref('0px')
const playing = ref(false)
let bscroll = ref(null)
let audioPlayer = ref(null)
const vdTimer = ref(null)
const reactiveData = reactive({
  lyricList: [],
  lyricIndex: 0,
  itemRefs: [],
  lyricStr: '',
  reactiveLyric: null,
  currentTimeStr: '00:00',
  endTimeStr: '00:00',
  vdProgress: 0,
  showLines: 0,
  audioSrc: 'https://mp3.haoge500.com/upload/320/2021/05/12/1197161.mp3'
})
const {
  lyricList,
  lyricIndex,
  lyricStr,
  reactiveLyric,
  currentTimeStr,
  endTimeStr,
  vdProgress,
  audioSrc,
  showLines
} = toRefs(reactiveData)

watch(() => currentTime.value, (val, oval) => {
  let center = Math.floor(reactiveData.showLines / 2)
  if (val * 1000 > reactiveData.lyricList[reactiveData.lyricIndex + 1].time) {
    if (reactiveData.lyricIndex >= reactiveData.lyricList.length) return;
    reactiveData.lyricIndex += 1
    if (reactiveData.lyricIndex > center) {
      bscroll.value.scrollToElement(reactiveData.itemRefs[reactiveData.lyricIndex - center], 1000)
    }
  }
})
onBeforeUpdate(() => {
  reactiveData.itemRefs = [];
})

onMounted(() => {
  // 获取歌词文件
  reactiveData.lyricStr = loadFile('src/assets/homeland.lrc')
  // 歌词文件进行Lyric封装解构
  let lyric = new Lyric(reactiveData.lyricStr)
  reactiveData.reactiveLyric = lyric
  // 页面呈现
  reactiveData.lyricList = lyric.lines;
  //歌词补偿
  if (lyric.tags['offset']) {
    reactiveData.lyricList.forEach(item => item.time -= parseInt(lyric.tags['offset']))
  }
  // 获取top和bottom的高度，进行歌词content高度计算
  bottomHeight.value = useRect(document.getElementById('bottom')).height + 'px'
  topHeight.value = useRect(document.getElementById('top')).height + 'px'
  // 获取歌词一行高度
  nextTick(() => {
    let audio = getAudioInstance()
    if (!audio) {
      return;
    }
    audio.load();
    audio.addEventListener("ended", () => {
      playing.value = false;
      reactiveData.currentTimeStr = '00:00'
    })
    console.log(audio);
    audio.oncanplay = () => {
      reactiveData.endTimeStr = realFormatSecond(audio.duration)
    }
    let singleHeight = useRect(reactiveData.itemRefs[1]).height + 10
    let allHeight = useRect(document.getElementsByClassName('wrapper-lyric')[0]).height
    // 页面呈现行数
    reactiveData.showLines = Math.ceil(allHeight / singleHeight)
  })
})

// VUE3页面循环绑定ref
const setItemRef = (el) => {
  if (el) {
    reactiveData.itemRefs.push(el)
  }
}
const onSliderChange = (value) => {
  console.log(value);
  if (!value) return;
  const audio = getAudioInstance()
  if (!audio) {
    return
  }
  // console.log((audio.duration * value * 0.01).toFixed(1));
  // currentTime.value = (audio.duration * value * 0.01).toFixed(1)
  // audio.currentTime = (audio.duration * value * 0.01).toFixed(1)
}

const getAudioInstance: any = () => {
  return audioPlayer.value
}
const touchHandler = (el) => {
  console.log(el);
}
const onPlay = () => {
  const audio = getAudioInstance()
  if (!audio) {
    return
  }
  audio.play()
  playing.value = true;
  // 设置进度条
  vdTimer.value = setInterval(() => {
    handleProgress()
  }, 10)
}
const onPause = () => {
  const audio = getAudioInstance()
  if (!audio) {
    return
  }
  audio.pause()
  playing.value = false;
  vdTimer.value && clearInterval(vdTimer.value)
}
const handleProgress = () => {
  let audio = getAudioInstance()
  if (!audio) return
  let curTime: number = audio.currentTime.toFixed(1)
  let duration: number = audio.duration.toFixed(1);
  reactiveData.currentTimeStr = realFormatSecond(audio.currentTime)
  reactiveData.endTimeStr = realFormatSecond(audio.duration)
  reactiveData.vdProgress = parseInt((curTime / duration).toFixed(2) * 100)
  currentTime.value = audio.currentTime
}
const realFormatSecond = (second) => {
  var secondType = typeof second;
  if (secondType === "number" || secondType === "string") {
    second = parseInt(second);
    var hours = Math.floor(second / 3600);
    second = second - hours * 3600;
    var mimute = Math.floor(second / 60);
    second = second - mimute * 60;
    return ("0" + mimute).slice(-2) + ":" + ("0" + second).slice(-2);
  } else {
    return "0:00:00";
  }
}
</script>

<style scoped>
.listen-book {
  padding-bottom: v-bind(bottomHeight);
  overflow: hidden;
}

.book-cover {
  height: 226px;
  margin: 20px auto 0 auto;
  border-radius: 7.56px;
}

.wrapper-lyric {
  height: calc(100vh - 246px - 2rem - 1.5rem - v-bind(bottomHeight) - v-bind(topHeight));
  width: 100%;
  overflow: hidden;
  left: 0;
  right: 0;
}
</style>
